package com.geeyuu.android.activity;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.view.KeyEvent;
import android.widget.Toast;

import com.geeyuu.android.service.IMService;
import com.geeyuu.android.service.ReceiveMsgHandle;
import com.geeyuu.android.service.ServiceManager;
import com.geeyuu.android.utils.AndroidUtil;
import com.geeyuu.android.utils.LogUtil;
import com.umeng.analytics.MobclickAgent;

public class BaseActivity extends Activity {
    
    protected String TAG = "not_set";
    protected boolean isWatingMsgFromService = false;
    
    protected boolean isForbidBackKey = false;
    private ServiceManager mServiceManager;
    
    boolean isAutoCloseDialog = false;
    private ProgressDialog pd = null;
    
    private static final int TIME_OUT = 50 * 1000;

    /**
     * @param title
     * @param content
     * @param isAutoClose 同步命令，会自动关闭
     */
    protected void showProgressDialog(String title, CharSequence content, boolean isAutoClose){
        if(null == pd){
            pd = new ProgressDialog(this);
            pd.setIndeterminate(true);
            pd.setCancelable(true);
            pd.setTitle(title);
            pd.setMessage(content);
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    isWatingMsgFromService = false;
                    isAutoCloseDialog = false;
                    if(null != timerTask){
                        timerTask.cancel();
                    }
                    if(null != timer){
                        timer.cancel();
                    }
                }
            });
        }
        if(!pd.isShowing()){
            isAutoCloseDialog = isAutoClose;
            pd.show();
        }
    }
    
    /**
     * 
     * @param titleRes
     * @param content
     * @param isAutoClose 同步命令，会自动关闭
     */
    protected void showProgressDialog(int titleRes, int content, boolean isAutoClose){
        if(null == pd){
            pd = new ProgressDialog(this);
            pd.setIndeterminate(true);
            pd.setCancelable(true);
            pd.setTitle(titleRes);
            pd.setMessage(getString(content));
            pd.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    isAutoCloseDialog = false;
                    isWatingMsgFromService = false;
                    if(null != timerTask){
                        timerTask.cancel();
                    }
                    if(null != timer){
                        timer.cancel();
                    }
                }
            });
        }
        if(!pd.isShowing()){
            isAutoCloseDialog = isAutoClose;
            pd.show();
        }
    }
    
    protected void cancelProgressDialog(){
        if(null != pd && pd.isShowing()){
            pd.cancel();
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && isForbidBackKey){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    protected void startBindService(){
        if(TAG.equals("not_set")){
            LogUtil.e(TAG, "没有设置TAG，不允许绑定");
            return;
        }
        if(null == mServiceManager){
            mServiceManager = new ServiceManager(getApplicationContext(), IMService.class, new BaseHandler(this, TAG, 0));
        }
    }
    
    protected void stopBindService(){
        if(TAG.equals("not_set")){
            LogUtil.e(TAG, "没有设置TAG，不允许解除绑定");
            return;
        }
        if(null != mServiceManager){
            mServiceManager.doUnbindService(TAG);
        }
    }
    
    private TimerTask timerTask = null;
    private Timer timer = null;
    private int cmd;
    
    /**
     * 带超时的同步命令
     * @param command
     * @param bundle
     */
    protected void sendMsgToService(int command, Bundle bundle){
        cmd = command;
        if(!AndroidUtil.isNetworkAvailable(this)){
            LogUtil.w(TAG, "没有网络连接");
            Toast.makeText(getApplicationContext(), "没有网络连接", Toast.LENGTH_SHORT).show();
            onReceiveMsgFromService(cmd, null, false);
            return;
        }
        isWatingMsgFromService = true;
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if(isWatingMsgFromService){
                    LogUtil.i(TAG, "activity请求超时");
                    isWatingMsgFromService = false;
                    Looper.prepareMainLooper();
                    if(isAutoCloseDialog){
                        isAutoCloseDialog = false;
                        cancelProgressDialog();
                    }
                    onReceiveMsgFromService(cmd, null, false);
                }
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, TIME_OUT);
        Message message = new Message();
        message.obj = TAG;
        message.what = command;
        if(null != bundle){
            message.setData(bundle);
        }
        if(null != mServiceManager){
            try {
                mServiceManager.sendMsgToService(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }else{
            LogUtil.e(TAG, "mServiceManager没有初始化");
        }
    }
    
    private void onReceiverMsgFromHandler(int cmd, Bundle bundle, int errorCode){
        if(isWatingMsgFromService){
            isWatingMsgFromService = false;
            if(null != timerTask){
                timerTask.cancel();
            }
            if(null != timer){
                timer.cancel();
            }
            if(isAutoCloseDialog){
                isAutoCloseDialog = false;
                cancelProgressDialog();
            }
            onReceiveMsgFromService(cmd, bundle, errorCode == ReceiveMsgHandle.ERROR_CODE_OK ? true : false);
        }else{
            LogUtil.e(TAG, "没有消息在等待, cmd: " + cmd);
        }
    }
    
    protected void onReceiveMsgFromService(int cmd, Bundle bundle, boolean isMsgNormal){
    }
    
    protected void onConnectServiceCallBack(){
    }
    
    public static class BaseHandler extends Handler{
        
        private final int type;
        private final WeakReference<Activity> activity;
        public String tag;
        
        public BaseHandler(Activity activity, String tag, int type){
            this.activity = new WeakReference<Activity>(activity);
            this.tag = tag;
            this.type = type;
        }
        
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(type == 0){
                if(msg.what == -1){
                    ((BaseActivity)activity.get()).onConnectServiceCallBack();
                }else{
                    LogUtil.i(tag, tag + " 收到消息");
                    ((BaseActivity)activity.get()).onReceiverMsgFromHandler(msg.what, msg.getData(), msg.arg1);
                }
            }else{
                if(msg.what == -1){
                    ((Activity1)activity.get()).onConnectServiceCallBack();
                }else{
                    LogUtil.i(tag, tag + " 收到消息");
                    ((Activity1)activity.get()).onReceiverMsgFromHandler(msg.what, msg.getData(), msg.arg1);
                }
            }
        }
        
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LogUtil.v(TAG, "onCreate");
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtil.v(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
        LogUtil.v(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
        LogUtil.v(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        LogUtil.v(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        isWatingMsgFromService = false;
        super.onDestroy();
        LogUtil.v(TAG, "onDestroy");
    }
    
}
